package com.thiswhyme.log.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务配置
 * TODO 替换为真实配置
 * Created by thiswhyme on 2020/10/11
 */
@Slf4j
@Configuration
@EnableAsync
@ComponentScan("com.thiswhyme")
public class AsyncConfig {

    @Bean(name = "defaultExecutor")
    public Executor logExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(10);
        threadPool.setQueueCapacity(50);
        threadPool.setMaxPoolSize(20);
        threadPool.setRejectedExecutionHandler(new BlockingRunsPolicy());
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        threadPool.setThreadNamePrefix("Default-Thread-");
        threadPool.initialize();
        return threadPool;
    }

    /**
     * 自定义拒绝策略-阻塞
     */
    public static class BlockingRunsPolicy implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                log.warn("【defaultExecutor】线程池&队列已满，阻塞任务提交");
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                log.error("【defaultExecutor】线程池拒绝策略执行异常，errMsg：{}", e.getMessage());
            }
        }
    }
}
